package logic

import (
	"context"
	"errors"
	"shop/cache"
	"shop/models"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodsAddLogic) GoodsAdd(in *shopRpc.GoodsAddRequest) (*shopRpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	goods := models.Goods{
		Name:   in.Name,
		Price:  float64(in.Price),
		Stock:  int(in.Stock),
		Img:    in.Img,
		Status: int(in.Status),
	}
	err := goods.GoodsAdd(models.DB)
	if err != nil {
		return nil, errors.New("添加失败")
	}

	err = cache.SyncStock(int64(goods.ID), int64(goods.Stock))
	if err != nil {
		return nil, errors.New("虚拟同步失败")
	}
	return &shopRpc.GoodsAddResponse{
		Id: int64(goods.ID),
	}, nil
}
